<?php

namespace WeChat\Controller;

use Think\Log;

class MemberController extends BaseController {

    private $uid = 0;

    protected function _initialize() {
        parent::_initialize();

        $this->uid = $this->login();
//  $this->uid = 6069;//===delete
    }

    /**
     * 会员中心
     */
    public function center() {


        $member_model = D('Member');
        $old_nickname = get_user_info_wechat($this->uid, 'nickname');
        $member_info = get_user_info_wechat($this->uid); //current member information
        $info = get_user_info_wechat($this->uid, 'info');
        $nickname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $info['nickname']);

        $old_nickname == '' ? $member_model->where('id=' . $this->uid)->save(array('nickname' => $nickname)) : true;

        //会员等级
        $array_member_level = D('MemberLevel')->member_level($this->uid);

        if (!$array_member_level['status']) {

            $this->error($array_member_level['msg']);
        }

        $member_info['level'] = $array_member_level['msg']['level'];

        $member_count = $member_model->max("id");  //total membership
        //会员父级信息
        if ($member_info['pid'] == 0) {

            $this->assign("pnickname", "官网");
        } else {

            $pmember = get_user_info_wechat($member_info['pid']);

            $this->assign("pnickname", $pmember['nickname']);
        }

        //member income
        $array_member_income = $member_model->member_income($this->uid);
        $reslut = $member_model->checkManage($this->uid);


        if (!$array_member_income['status']) {

            $this->error($array_member_income['msg']);
        }

        $member_income = $array_member_income['msg'];

        //member balance
        $array_member_balance = $member_model->member_balance($this->uid);

        if (!$array_member_balance['status']) {

            $this->error($array_member_balance['msg']);
        }

        $member_balance = $array_member_balance['msg'];
        $reslut == 1 ? $this->assign("manage", 1) : $this->assign("manage", 0);

        $this->assign("member_count", $member_count);

        $this->assign("member", $member_info);
        $this->assign("total_spend", $member_info['total_spend']);
        $this->assign("member_income", $member_income);

        $this->assign('member_balance', $member_balance);

        $this->display();
    }

    /*
     * 会员钱包
     * 
     * @param
     */

    public function members_wallet() {

        $member_id = $this->uid;

        //总收益
        $array_member_income = D('Member')->member_income($member_id);

        if (!$array_member_income['status']) {

            $this->error($array_member_income['msg']);
        }

        $member_income = $array_member_income['msg'];

        $this->assign('member_income', $member_income);

        //三级分佣
        $array_member_commission = D('MemberCommission')->member_commission($member_id);

        if (!$array_member_commission['status']) {

            $this->error($array_member_commission['msg']);
        }

        $member_commission = $array_member_commission['msg']['num'];

        $this->assign('member_commission', $member_commission);

        //全返奖励
        $array_member_fullback = D('MemberFullback')->member_fullback($member_id);

        if (!$array_member_fullback['status']) {

            $this->error($array_member_fullback['msg']);
        }

        $member_fullback = $array_member_fullback['msg']['num'];

        $this->assign('member_fullback', $member_fullback);

        //团队奖励
        $array_member_teamdividend = D('MemberTeamdividend')->member_teamdividend($member_id, 0);

        if (!$array_member_teamdividend['status']) {

            $this->error($array_member_teamdividend['msg']);
        }

        $member_teamdividend = $array_member_teamdividend['msg']['num'];

        $this->assign('member_teamdividend', $member_teamdividend);
        //董事分红
        $array_member_managerewards = D('MemberManagerewards')->manage_teamdividend($member_id);

        if (!$array_member_managerewards['status']) {

            $this->error($array_member_managerewards['msg']);
        }

        $array_member_managerewards = $array_member_managerewards['msg']['num'];


        $this->assign('manage_meamdividend', $array_member_managerewards);



        //公排奖励
        $array_memer_publicrow = D('Gongpai')->gp_reward($member_id, C('PR_LIMIT_LEVEL'), C('PR_SEEPOINT_RAWARD'));

        if (!$array_memer_publicrow['status']) {

            $this->error($array_memer_publicrow['msg']);
        }

        $member_publicrow = $array_memer_publicrow['msg'];

        $this->assign('member_publicrow', $member_publicrow);


        //提现金额
        $array_member_cash = D('MemberCash')->member_cash($member_id, 0);

        if (!$array_member_cash['status']) {

            $this->error($array_member_cash['msg']);
        }

        $member_cash = $array_member_cash['msg']['num'];

        $this->assign('member_cash', $member_cash);

        //转赠金额
        #转出
        $array_member_sendscore = D('MemberSendscore')->member_sendscore($member_id, 1);

        if (!$array_member_sendscore['status']) {

            $this->error($array_member_sendscore['msg']);
        }

        $member_score['send'] = $array_member_sendscore['msg']['num'];

        #获赠
        $array_member_getscore = D('MemberSendscore')->member_sendscore($member_id, 2);

        if (!$array_member_getscore['status']) {

            $this->error($array_member_getscore['msg']);
        }

        $member_score['get'] = $array_member_getscore['msg']['num'];

        $this->assign('member_score', $member_score);

        //会员余额
        $array_member_balance = D('Member')->member_balance($member_id);

        if (!$array_member_balance['status']) {

            $this->error($array_member_balance['status']);
        }

        $member_balance = $array_member_balance['msg'];

        $this->assign('member_balance', $member_balance);

        $this->display();
    }

    /*
     * 积分转赠
     * 
     * @param
     */

    public function send_score() {

        if (IS_POST) {

            /*
             * 重新处理数据
             * $data = I('post.');
             * $member_balance = $data['member_balance'];
             * $send_score = $data['total'];
             */

            $_POST['status'] = 1;

            $_POST['send_no'] = '';

            $create_data = D('MemberSendscore')->create();

            if ($create_data) {

                $row = D('MemberSendscore')->add();

                if ($row) {

                    /*
                     * 更改会员信息，暂时不填（因为会员的多种动态收入没有总的余额字段）
                     * D('Member')->where(' id ='.$data['user_id'])->setDec('balance', $data['total']);
                     * D('Member')->where(' id ='.$data['ruser_id'])->setInc('balance', $data['total']);
                     */

                    $this->error('积分转赠成功！');
                } else {

                    $this->error('积分转赠操作失败！');
                }
            } else {

                $this->error('数据创建失败，请重试！');
            }
        }

        //计算用户余额

        $array_member_balance = D('Member')->member_balance($this->uid);

        if (!$array_member_balance['status']) {

            $this->error($array_member_balance['msg']);
            exit;
        }

        $member_balance = $array_member_balance['msg'];

//        $this->assign('balance', 100);

        $this->assign('balance', $member_balance);

//        $this->assign('user_id', 6065);

        $this->assign('user_id', $this->uid);

        $this->display();
    }

    /*
     * 会员转赠积分列表
     * 
     * @param string condition  数据条件 send 转出积分 get 获赠积分
     */

    public function sendscore_list($condition = 'send') {

        $get_condition = I('get.condition', 'send');

        $type = 1;

        if ($get_condition == 'get') {

            $type = 2;
        } else if ($get_condition == 'send') {

            $type = 1;
        } else {
            
        }

        $array_score_list = D('MemberSendscore')->member_sendscore($this->uid, $type);

        if (!$array_score_list['status']) {

            $this->error($array_score_list['msg']);
            exit;
        }

        $this->assign('score_list', $array_score_list['msg']['list']);

        $this->assign('score', $array_score_list['msg']['num']);

        $this->assign('current_tab', $get_condition);

        $this->display();
    }

    /*
     * ajax 根据会员编号查看用户是否存在(send_score)
     * 
     * @param string id 会员id
     * 
     * @param string identify store 专卖店
     */

    public function check_member() {

        if (IS_AJAX) {

            $data = I('post.');

            //不能给自己转账
            if ($data['id'] == $this->uid) {

                $this->error('抱歉，您不能给自己转账！');
            }

            //查询转赠会员信息
            $where = '1=1';

            if ($data['identify'] == 'store') {

                $where .=' and is_store = 1';
            }

            $where .= ' and id =' . $data['id'];

            $member_info = D('Member')->where($where)->field('id, nickname, is_store')->find();

            if (empty($member_info)) {

                $this->error('编号【' . $data['id'] . '】的会员不是专卖店会员或者不存在！');
            } else {

                $this->success($member_info);
            }
        }
    }

    /*
     * 会员提现方法 (银行卡提现 和 微信提现)
     * 
     * @param
     */

    public function member_cash() {

        if (IS_POST) {

            $post_data = I('post.');
            $_POST['nickname'] = get_user_info_wechat($this->uid, 'nickname');
            $_POST['fee'] = $post_data['total'] * $post_data['fee_scale'] / 100;

            $_POST['total_fact'] = $post_data['total'] * (100 - $post_data['fee_scale']) / 100;

            $data = D('MemberCash')->create();

            if ($data) {

                $row = D('MemberCash')->add();  //添加提现数据

                if ($row) {

                    $this->success('提现成功！');
                } else {

                    $this->error('提现异常,请重试！');
                }
            } else {

                $this->error('数据获取失败，请重试！');
            }
        } else {

            //获取用户的银行卡信息，没有则提示用户添加银行卡

            $member_bank = D('MemberBank')->get_member_bankcard($this->uid, TRUE);

            if (empty($member_bank['msg'])) {

                $this->error('请先完善银行卡信息！', U('add_member_bankCard', array('flag' => 'firstcash')));
            }

            //会员余额
            $array_member_balance = D('Member')->member_balance($this->uid);

            if (!$array_member_balance['status']) {

                $this->error($array_member_balance['msg']);
            }

            $member_balance = $array_member_balance['msg'];

            //处理银行卡号 待处理
//        $member_balance['account_bank'] = deal_string( $member_balance['account_bank']); exit;

            $this->assign('member_bank', $member_bank['msg']);

            $this->assign('balance', $member_balance);

            $this->assign('withdrawal_scale', C('OT_CASH_WITHDRAWAL_SCALE'));

            $this->display();
        }
    }

    /**
     * 添加会员银行卡
     */
    public function add_member_bankCard() {

        $flag = I('get.flag', 'addcard');

        if (IS_POST) {

            if ($flag == 'firstcash') {

                $_POST['is_default'] = 1;   //首次添加，自动设置为默认银行卡
            }

            $data = D("MemberBank")->create();

            $row = D("MemberBank")->add($data);

            if ($row) {

                if ($flag == 'firstcash') {

                    $this->success("√银行卡信息设置成功。", U('member_cash'));
                } else {

                    $this->success("√银行卡信息设置成功。", U('bankcard_list'));
                }
            } else {

                $this->error("×银行卡信息设置失败。");
            }
        } else {

            $this->assign('user_id', $this->uid);

            $this->display();
        }
    }

    /*
     * 编辑会员银行卡信息
     */

    public function edit_member_bankcard() {

        $member_bank_model = D('MemberBank');

        if (IS_POST) {

            $data = I('post.');

            if (($data['default'] <> $data['is_default']) && $data['is_default'] == 1) {

                $set_default_bank = $member_bank_model->handle_member_bankcard('setdefault', $data['id']);

                if (!$set_default_bank['status']) {

                    $this->error($set_default_bank['msg']);
                } else {

                    $member_bank_model->save($data);

                    $this->success($set_default_bank['msg'], U('bankcard_list'));
                }
            } else {

                $row = $member_bank_model->save($data);

                if ($row) {

                    $this->success('银行卡编辑成功！', U('bankcard_list'));
                } else {

                    $this->error('银行卡编辑失败！');
                }
            }
        } else {

            //获取会员的所有银行卡信息

            $card_id = I('get.id');

            $member_bank_data = $member_bank_model->get_member_bankcard($this->uid, FALSE, $card_id);

            if (!$member_bank_data['status']) {

                $this->error($member_bank_data['msg'], U('add_member_bankcard'));
            }

            $this->assign('bankcard', $member_bank_data['msg']);

            $this->display();
        }
    }

    /*
     * ajax 处理会员银行卡
     * 
     * @param 传递参数 type  del 删除会员银行卡  id 银行卡唯一标识
     * 
     */

    public function handle_bankcard() {

        if (IS_AJAX) {

            $data = I('post.');
            $result_array = D('MemberBank')->handle_member_bankcard($data['typt'], $data['id']);

            if (!$result_array['status']) {

                $this->error($result_array['msg']);
            } else {
                $this->success($result_array['msg']);
            }
        }
    }

    /*
     * 会员提现记录
     * 
     * @param string  condition verify 已审核 noverify 未审核
     */

    public function cash_record($condition = 'verify') {

        $get_condition = I('get.condition', 'verify');

        $type = 1;

        if ($get_condition == 'noverify') {

            $type = 2;
        } else if ($get_condition == 'verify') {

            $type = 1;
        } else {
            
        }

        $array_cash_list = D('MemberCash')->member_cash($this->uid, $type);

        if (!$array_cash_list['status']) {

            $this->error($array_cash_list['msg']);
            exit;
        }

//        dump($array_cash_list['msg']['list']);exit;
        $this->assign('cash_list', $array_cash_list['msg']['list']);

        $this->assign('cash', $array_cash_list['msg']['num']);

        $this->assign('current_tab', $get_condition);

        $this->display();
    }

    /*
     * 会员银行卡列表
     * 
     * @param
     */

    public function bankcard_list() {

        $member_bankcards = D('MemberBank')->get_member_bankcard($this->uid, FALSE);

        if (empty($member_bankcards['msg'])) {

            $this->error('您还没有添加银行卡，去绑定银行卡！', U('Member/add_member_bankCard', array('flag' => 'addcard')));
        }

        $this->assign('bankcard_list', $member_bankcards['msg']);

        $this->display();
    }

    /*
     * 会员奖励详情列表
     * 
     * @param  三级分佣 m_commission
     * 
     * @param  会员全返 m_fullback
     * @param  等级分红 m_teamdividend
     * @param  公排奖励 m_publirow
     */

    public function reward_list() {

        $status = I('get.status', 'm_commission');

        $member_id = $this->uid;

        switch ($status) {
            //全返
            case 'm_fullback':

                $array_list = D('MemberFullback')->member_fullback($member_id);

                $this->assign('HEAD_TITLE', '全返列表');

                break;

            //团队分红
            case 'm_teamdividend':

                $array_list = D('MemberTeamdividend')->member_teamdividend($member_id);

                $this->assign('HEAD_TITLE', '团队分红');

                break;
            //董事分红
            case 'm_manage':

                $array_list = D('MemberManagerewards')->manage_teamdividend($member_id);
                $this->assign('HEAD_TITLE', '董事分红');

                break;

            //公排
            case 'm_publicrow':

                $array_list = D('Gongpai')->gp_reward($member_id, C('PR_LIMIT_LEVEL'), C('PR_SEEPOINT_RAWARD'));

                $this->assign('HEAD_TITLE', '公排奖励');

                break;

            //三级分佣
            default:

                $array_list = D('MemberCommission')->member_commission($member_id);

                $this->assign('HEAD_TITLE', '三级分佣');

                break;
        }

        if (!$array_list['status']) {

            $this->error($array_list['msg']);
        }

        $this->assign('data', $array_list['msg']);
        $this->assign('flag', $status);

        $this->display();
    }

    /**
     * 分销中心
     */
    public function distribution() {

        $this->display();
    }

    /**
     * 富豪榜
     */
    public function richList() {

        $member = get_user_info_wechat($this->uid);

        $teams = M('Member')->field("id,nickname,info,score,balance,total_spend,lft,rgt,create_time")
                        ->where('balance > 0')
                        ->order("balance desc, id asc")->select();
        foreach ($teams as $key => $item) {
            $teams[$key]["info"] = json_decode($item['info'], TRUE);
            $teams[$key]["sub"] = ($item['rgt'] - $item['lft'] - 1) / 2;
        }

        //排名
        $ranking = M('Member')->where("total >= " . $member['total'])->order("total desc,id asc")->count();

        $this->assign("member", $member);
        $this->assign("ranking", $ranking);
        $this->assign("teams", $teams);
        $this->display();
    }

    /**
     * 积分榜
     */
    public function scoreList() {
        $member = get_user_info_wechat($this->uid);

        $teams = M('Member')->field("id,nickname,info,score,balance,total_spend,lft,rgt,create_time")
                        ->where('score>0')->limit(20)
                        ->order("score desc ,id asc")->select();
        foreach ($teams as $key => $item) {
            $teams[$key]["info"] = json_decode($item['info'], TRUE);
            $teams[$key]["sub"] = ($item['rgt'] - $item['lft'] - 1) / 2;
        }
        // dump($teams);
        $ranking = M('Member')->where("score >= " . $member['score'])->order("score desc,id asc")->count();

        $this->assign("member", $member);
        $this->assign("ranking", $ranking);
        $this->assign("teams", $teams);
        $this->display();
    }

    /*
     * 会员佣金
     * @总佣金、待审核佣金、已发放佣金
     */

    public function brokerage() {
        $membercommission_model = D('MemberCommission');
        $map['userid'] = $this->uid;
        $commission_info = $membercommission_model->where($map)->sum('commission');

        $this->assign('total', $commission_info);
        $this->display();
    }

    /*
     * 佣金详情
     */

    public function brokeragedetail($type = 0) {
        $membercommission_model = D('MemberCommission');
        $map['userid'] = $this->uid;
        switch ($type) {
            case 0:
                $map['deal_status'] = 1;
                $total = $membercommission_model->where($map)->sum('commission');
                $commission_info = $membercommission_model->where($map)->select();
                break;
            case 1:
                $map['deal_status'] = 0;
                $total = $membercommission_model->where($map)->sum('commission');
                $commission_info = $membercommission_model->where($map)->select();
                break;
        }
        $this->assign('total', $total);
        $this->assign('detail', $commission_info);
        $this->display();
    }

    /**
     * 我的佣金
     */
    public function brokerage_old() {

        $paySql = "SELECT sum(commission) AS tc FROM kmeen_member_commission AS mc "
                . "LEFT JOIN kmeen_order AS o"
                . " ON mc.order_no = o. NO "
                . "WHERE mc.userid =  {$this->uid} "
                . "AND o.pay_status = 2 "
                . "AND o.status = 1 "
                . "AND o.send_status = 1";
        $payTotalResult = M()->query($paySql);

        $payTotal = $payTotalResult['0']['tc'];

        $receiptSql = "SELECT sum(commission) AS tc FROM kmeen_member_commission AS mc "
                . "LEFT JOIN kmeen_order AS o"
                . " ON mc.order_no = o. NO "
                . "WHERE mc.userid =  {$this->uid} "
                . "AND o.pay_status = 2 "
                . "AND o.status = 2 "
                . "AND o.send_status = 2";

        $receiptTotalResult = M()->query($receiptSql);
        $receiptTotal = $receiptTotalResult['0']['tc'];


        $cancelSql = "SELECT sum(commission) AS tc FROM kmeen_member_commission AS mc "
                . "LEFT JOIN kmeen_order AS o"
                . " ON mc.order_no = o. NO "
                . "WHERE mc.userid =  {$this->uid} "
                . "AND o.status = 2 ";

        $cancelTotalResult = M()->query($cancelSql);
        $cancelTotal = $cancelTotalResult['0']['tc'];


        $passSql = "SELECT sum(commission) AS tc FROM kmeen_member_commission AS mc "
                . "LEFT JOIN kmeen_order AS o"
                . " ON mc.order_no = o. NO "
                . "WHERE mc.userid =  {$this->uid} "
                . "AND mc.deal_status = 1 ";

        $passTotalResult = M()->query($passSql);
        $passTotal = $passTotalResult['0']['tc'];

        $this->assign("payTotal", $payTotal);
        $this->assign("receiptTotal", $receiptTotal);
        $this->assign("cancelTotal", $cancelTotal);
        $this->assign("passTotal", $passTotal);
        $this->display();
    }

    /**
     * 佣金明细
     */
    public function brokerageDetail_old($type = 0) {
        $countFields = " sum(commission) ";
        $fields = " mc.*";

        if ($type == 0) {
            $where = "AND o.pay_status = 2 "
                    . "AND o.status = 1 ";
        } else if ($type == 1) {
            $where = "AND o.pay_status = 1 "
                    . "AND o.status = 2 "
                    . "AND o.send_status = 2";
        } else if ($type == 2) {

            $where = "AND o.status = 2 ";
        } else if ($type == 3) {

            $where = "AND mc.deal_status = 1 ";
        }


        $sqlTotal = "SELECT {$countFields} AS tc FROM kmeen_member_commission AS mc "
                . "LEFT JOIN kmeen_order AS o"
                . " ON mc.order_no = o. NO "
                . "WHERE mc.userid =  {$this->uid} " . $where;

        $totalResult = M()->query($sqlTotal);
        $total = $totalResult['0']['tc'];
        $this->assign("total", $total);

        $sqlDetail = "SELECT {$fields} FROM kmeen_member_commission AS mc "
                . "LEFT JOIN kmeen_order AS o"
                . " ON mc.order_no = o. NO "
                . "WHERE mc.userid =  {$this->uid} " . $where;

        $list = M()->query($sqlDetail);
        $this->assign("list", $list);


        $this->display();
    }

    /**
     * 提现
     */
    public function cash() {
        if (IS_POST) {
            $total = I("post.total");
            $balance = I('post.balance');
            if (!$total) {
                $this->error("请输入提现金额");
            }
            if ($total < 50) {
                $this->error("提现金额必须大于50");
            }
            if ($total > $balance) {
                $this->error("您的余额不足！");
            }
            $data = D("MemberCash")->create();
            $data['create_time'] = $data['update_time'] = time();
            $data['nickname'] = get_user_info_wechat($this->uid, 'nickname');
            $cid = D("MemberCash")->add($data);

            if ($cid) {
                M("Member")->where("id={$this->uid }")->setDec('balance', $total);
                $this->success("提现申请成功");
            } else {
                $this->error("提现申请失败");
            }
        } else {

            $bank = D("MemberBank")->where(array("user_id" => array("eq", $this->uid)))->find();
            if (!$bank) {
                $this->error("请先完善银行卡信息", U("bankCard"));
            }
            $this->assign("bank", $bank);
            $this->assign("balance", get_user_info_wechat($this->uid, "balance"));

            $this->display();
        }
    }

    /**
     * 微信红包提现
     */
    public function cashRed() {
        $member = get_user_info_wechat($this->uid);
        $member_balance = $member['balance'];
        if (IS_POST) {
            $total = I("post.total");
            if (!$total) {
                $this->error("请输入提现金额");
            }

            $c = C('FX_MAX_CASH');
            if (empty($c)) {
                $c = 1;
            }

            if ($total < $c || $total > 200) {
                $this->error("红包提现金额必须在{$c}到200之间");
            }

            if ($total > $member_balance) {
                $this->error("余额不足");
            }
            $billno = $this->wechat->getBillNo();
            $result = $this->wechat->sendRedPack($member['openid'], $billno, $total * 100, C('WEB_SITE_TITLE'), C('WEB_SITE_SLOGAN'), '提现红包', '提现红包');

            $log = array();
            $log['user_id'] = $this->uid;
            $log['name'] = $member['nickname'];
            $log['total'] = $total;
            $log['type'] = 1;
            $log['billno'] = $billno;
            $log['data'] = json_encode($result);
            $log['create_time'] = $log['update_time'] = time();
            D("MemerCashRed")->add($log);
            if ($result) {
                M("Member")->where("id={$this->uid }")->setDec('balance', $total);
                $this->success("提现申请成功");
            } else {
                $this->error("提现申请失败");
            }
        } else {
            $this->assign("balance", $member_balance);
            $this->display();
        }
    }

    /**
     * 提现记录
     */
    public function cashRecord() {
        $membercash_model = D('MemberCash');
        $map['userid'] = $this->uid;
        $cashrecord = $membercash_model->where($map)->select();
        $map['status'] = 1;
        $cash_total = $membercash_model->where($map)->sum('total');

        $this->assign('cashrecord', $cashrecord);
        $this->assign('total', $cash_total);
        $this->display();
    }

    /**
     * 我的团队
     */
    public function team() {
        $member = get_user_info_wechat($this->uid);

        $map['lft'] = array('gt', $member['lft']);
        $map['rgt'] = array('lt', $member['rgt']);
        $map['flag'] = array('eq', $member['flag']);

        $teamNum = array();
        $lvl = $member['lvl'];
        for ($index = 0; $index < C('FX_M_LEVEL'); $index++) {
            $lvl ++;
            $map['lvl'] = array('eq', $lvl);
            $teamNum[$index] = M('Member')->where($map)->count();
        }

        $this->assign("teamNum", $teamNum);
        $this->assign("level", C('FX_M_LEVEL'));
        $this->display();
    }

    /**
     * 我的团队详情
     */
    public function teamList($level) {
        if ($level > C('FX_M_LEVEL')) {
            $this->error("用户级别超过限制！");
        }

        $member = get_user_info_wechat($this->uid);

        $now_level = $member['lvl'] + $level;
        $map['lft'] = array('gt', $member['lft']);
        $map['rgt'] = array('lt', $member['rgt']);
        $map['flag'] = array('eq', $member['flag']);
        $map['lvl'] = array('eq', $now_level);

        $teams = M('Member')->field("id,nickname,info,score,balance,total_spend,lft,rgt,create_time")
                        ->where($map)->select();
        foreach ($teams as $key => $t) {
            //会员基本信息
            $teams[$key]['info'] = json_decode($t['info'], TRUE);
            //当前级别人数
            $teams[$key]['sub'] = ($t['rgt'] - $t['lft'] - 1) / 2;
        }
        $this->assign("teams", $teams);
        $this->display();
    }

    /**
     * 会员订单
     * @type 订单类型 all 所有订单 waitPay 待支付 waitSend 待发货 waitShou 代收货 finish已完成
     * 
     */
    public function order() {

        $type = I('get.type', 'all');

        $map['user_id'] = $this->uid;

        switch ($type) {
            case 'waitPay':
                $map['pay_status'] = array('lt', 2);
                $map['status'] = 1;

                break;
            case 'waitSend':
                $map['pay_status'] = array('eq', 2);
                $map['status'] = 1;
                $map['send_status'] = array('eq', 0);
                break;
            case 'wait':
                $map['pay_status'] = array('eq', 2);
                $map['status'] = 1;
                $map['send_status'] = array('eq', 1);

                break;
            case 'finish':
                $map['pay_status'] = array('eq', 2);
                $map['status'] = 1;
                $map['send_status'] = array('eq', 2);
                break;
            default:
                $map['status'] = array('neq', 3); //status等于3表示用户删除订单
        }

        $order_list = M('Order')->where($map)->order('id desc')->select();

        #根据订单取出订单商品
        foreach ($order_list as $k => $v) {

            $order_goods = M('OrderGoods')->where("order_no = '$v[order_no]'  and order_id = '$v[id]'")->Field('goods_id, title, cover, count, price')->select();

            $order_list[$k]['goods'] = $order_goods;

            $order_list[$k]['address'] = $v['province'] . '|' . $v['city'] . '|' . $v['area'] . '|' . $v['street'] . '|' . $v['address'];
        }

        $this->assign('list', $order_list);

        $this->assign('currentTab', $type);

        $this->display();
    }

    /*
     * 会员信息
     */

    public function profile() {

        $this->display();
    }

    /**
     * 我的资料
     */
    public function baseInfo() {
        if (IS_POST) {

            $member_model = D("Member");

            $data = $member_model->create();

            if ($data) {

                if ($member_model->save($data) !== false) {

                    $this->success("信息设置成功");
                } else {

                    $this->error("信息设置失败");
                }
            } else {

                $this->error($member_model->getError());
            }
        } else {

            $userinfo = get_user_info_wechat($this->uid);
            //dump($userinfo);
            $this->assign("baseinfo", $userinfo);

            $this->display();
        }
    }

    /**
     * 我的银行卡
     */
    public function bankCard() {

        $bank = D("MemberBank")->where(array("user_id" => array("eq", $this->uid)))->find();

        if (IS_POST) {

            $data = D("MemberBank")->create();

            if (!$bank) {

                $data['user_id'] = $this->uid;
                $data['status'] = 1;
                $data['create_time'] = $data['update_time'] = time();
                $cid = D("MemberBank")->add($data);

                if ($cid) {

                    $this->success("银行卡信息设置成功");
                } else {

                    $this->error("银行卡信息设置失败");
                }
            } else {

                $data['id'] = $bank['id'];
                $data['update_time'] = time();
                $cid = D("MemberBank")->save($data);

                if ($cid) {

                    $this->success("银行卡信息设置成功");
                } else {

                    $this->error("银行卡信息设置失败");
                }
            }
        } else {

            $this->assign("bank", $bank);

            $this->display();
        }
    }

    /*
     * 邀请入口；链接
     */

    public function invite($id) {

        echo $this->login(TRUE, $id);

        redirect(U("WeChat/Index/index"));
    }

    /**
     * 我的二维码
     */
    public function qrcode() {
        /*   $this->testimg();
          die(); */
        
        $this->login();
        
        $url_qrcode = get_user_info_wechat($this->uid, 'url_qrcode');
        
        $spend = get_user_info_wechat($this->uid, 'total_spend');
        
        $manage = M('member')->where('id=' . $this->uid)->field('manage')->find(); //执行董事标记
        
        $old_lvl_name = M('member')->where('id=' . $this->uid)->field('lvl_name')->find(); //等级昵称

        $member_model = D('Member');
        
        $old_nickname = get_user_info_wechat($this->uid, 'nickname');
        
        $info = get_user_info_wechat($this->uid, 'info');
        
        $nickname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $info['nickname']);

        $old_nickname == '' ? $member_model->where('id=' . $this->uid)->save(array('nickname' => $nickname)) : true;
        Log::write("用户昵称=====" . $nickname);

        if ($manage['manage'] == 1) {
            $now_lvl_name = '执行董事';
        } elseif ($spend < 399) {
            $now_lvl_name = '天使会员';
        } elseif (399 <= $spend && $spend < 799) {
            $now_lvl_name = '金牌会员';
        } elseif ($spend >= 799) {
            $now_lvl_name = '钻石会员';
        }

        if (empty($url_qrcode) || ($old_lvl_name['lvl_name'] !== $now_lvl_name)) {
            
            $lvl_name = $now_lvl_name;

            M('member')->where('id=' . $this->uid)->save(array('lvl_name' => $now_lvl_name));
            
            $member_info = get_user_info_wechat($this->uid);

            //获取微信二维码步骤
            //一、获取基础access_token 此值有效期7200s, 重复获取会导致上次的失效。每天有调用次数限制
            $this->wechat->getToken();  //获取基础access_token
            //二、获取用户永久二维码 根据access_token 获取ticket（传入的场景值会在微信返回 消息中返回给服务器处理）
            //根据 ticket获取到用户微信二维码
            $url_qrcode = $this->wechat->getQRUrl($this->uid, TRUE); //$this->uid 场景值id(scene_id)

            if(empty($url_qrcode)){
                
                Log::write('强制刷新获取qrcode_url');
                
                $this->wechat->getToken(false);
                
                $redirect_url = C('WEB_SITE_DOMAIN') . __SELF__;
                
                Log::write('刷新链接:'.$redirect_url);
                
                redirect($redirect_url);
            }
            
            $ticket = $this->wechat->getTicket();

            M("Member")->where('id=' . $this->uid)->setField('ticket', $ticket);

            $storage_qrcode_url = M('Member')->where('id=' . $this->uid)->setField('url_qrcode', $url_qrcode);

            $base_url = THINK_PATH . "../Public/front/headimg/"; //文件存储项目路径
            //    if ($storage_qrcode_url) {

            $http = new \Org\Net\Http();

            $image = new \Think\Image();

            //下载会员的二维码信息
            $qrcode_info = downloadImageFromWeiXin($url_qrcode);

            $member_qrcode_name = $base_url . $member_info['id'] . 'q' . '.jpg';

            $local_file = fopen($member_qrcode_name, 'w');

            if (false !== $local_file) {

                if (false != fwrite($local_file, $qrcode_info['body'])) {

                    fclose($local_file);
                }
            }

            //下载会员头像
            $head_url = $member_info['info']['headimgurl'];

            //判段头像不存在的情况
            if (empty($head_url)) {

                $head_url = THINK_PATH . "../Public/front/images/noavatar_big.jpg";
            }

            $head_name = $member_info['id'] . 'h' . '.jpg';

            $head_load = $base_url . $head_name;

            $http->curlDownload($head_url, $head_load);

            //会员头像 、二维码 与 背景图结合生成一张图片
            $url_background = THINK_PATH . "../Public/front/images/icon/erweima.jpg";

            //处理会员头像生成缩略图
            $url_head = $base_url . $member_info['id'] . 'h' . '.jpg';
            Log::write("h.jpg=====" . $member_info['id']);
            $img_head = $image->open($url_head); //=================
            $img_head->thumb(150, 150, \Think\Image::IMAGE_THUMB_SCALE)->save($url_head);
            //dump($a);exit;
            //处理会员二维码生成缩略图
            $url_qrcode = $base_url . $member_info['id'] . 'q' . '.jpg';
            $img_qrcode = $image->open($url_qrcode); //=====================bug
            Log::write("q.jpg=====" . $member_info['id']);
            $img_qrcode->thumb(380, 380, \Think\Image::IMAGE_THUMB_SCALE)->save($url_qrcode);

            $target_img = Imagecreatefromjpeg($url_background);
            $target_img_size = getimagesize($url_background);
            //dump($target_img_size);
            $head_img = Imagecreatefromjpeg($url_head);
            $qrcode_img = Imagecreatefromjpeg($url_qrcode);

            $center_x = ($target_img_size[0] - 380) / 2;

            //imagecopy php原生图片处理函数 拷贝图像的一部分
            //下例中：即拷贝qrcode_img 图像
            imagecopy($target_img, $qrcode_img, $center_x, 280, 0, 0, 380, 380);
            imagecopy($target_img, $head_img, $center_x, 90, 0, 0, 150, 150);

            //生成新图片名称
            $create_img_url = $base_url . $member_info['id'] . '.jpg';

            //用户字符串昵称    
            $nickname = '【' . get_str($member_info['nickname'], 0, 12) . '】';

            //定义字体名称。有些字体不能显示汉字，多试几次！
            $font = "C:\Windows\Fonts\msyhbd.ttf";

            $font_color = imagecolorallocate($target_img, 120, 180, 0); //字体颜色
            $font_color2 = imagecolorallocate($target_img, 250, 180, 0); //字体颜色
            imagefttext($target_img, 15, 0, 10, 10, $font_color, $font, '我是：');
            imagefttext($target_img, 15, 0, 320, 180, $font_color, $font, $nickname);
            imagefttext($target_img, 15, 0, 320, 220, $font_color2, $font, '级别:');
            imagefttext($target_img, 20, 0, 380, 220, $font_color2, $font, $lvl_name);
            imagefttext($target_img, 20, 0, 240, 700, $font_color, $font, '与我同行');
            imagefttext($target_img, 20, 0, 220, 750, $font_color, $font, '打开财富密码');

            $create_img = Imagejpeg($target_img, $create_img_url, 100);

            //                if ($create_img) {
            //
                //                    $qrcode_url = 'public/front/headimg/' . $member_info['id'] . '.jpg';
            //                }
            //       }
        }

        $src = 'Public/front/headimg/' . $this->uid . '.jpg';

        $this->assign('src', $src);
        $this->display();
    }

    public function testimg() {

        $url_qrcode = get_user_info_wechat($this->uid, 'url_qrcode');
        $spend = get_user_info_wechat($this->uid, 'total_spend');
        $manage = M('member')->where('id=' . $this->uid)->field('manage')->find();
        $old_lvl_name = M('member')->where('id=' . $this->uid)->field('lvl_name')->find();

        $member_model = D('Member');
        $old_nickname = get_user_info_wechat($this->uid, 'nickname');
        $info = get_user_info_wechat($this->uid, 'info');
        $nickname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $info['nickname']);

        $src = 'Public/front/headimg/6069.jpg';
        $res = file_exists($src);


        // echo"<meta charset='utf-8'><pre>";print_r( $url_head );die();

        $old_nickname == '' ? $member_model->where('id=' . $this->uid)->save(array('nickname' => $nickname)) : true;

        if ($manage['manage'] == 1) {
            $now_lvl_name = '执行董事';
        } elseif ($spend < 500) {
            $now_lvl_name = '天使会员';
        } elseif (500 < $spend && $spend < 799) {
            $now_lvl_name = '金牌会员';
        } elseif ($spend >= 799) {
            $now_lvl_name = '钻石会员';
        }
        if (empty($url_qrcode) || ($old_lvl_name['lvl_name'] !== $now_lvl_name) || $res !== 1) {

            $lvl_name = $now_lvl_name;
            M('member')->where('id=' . $this->uid)->save(array('lvl_name' => $now_lvl_name));
            $image = new \Think\Image();
            $url_background = THINK_PATH . "../Public/front/images/icon/erweima.jpg";

            //处理会员头像生成缩略图
            $url_head = THINK_PATH . "../Public/front/headimg/6069h.jpg";
            $img_head = $image->open($url_head);
            $img_head->thumb(150, 150, \Think\Image::IMAGE_THUMB_SCALE)->save($url_head);
            //dump($a);exit;
            //处理会员二维码生成缩略图
            $url_qrcode = THINK_PATH . "../Public/front/headimg/6069q.jpg";
            $img_qrcode = $image->open($url_qrcode); //=============
            $img_qrcode->thumb(380, 380, \Think\Image::IMAGE_THUMB_SCALE)->save($url_qrcode);

            $target_img = Imagecreatefromjpeg($url_background);
            $target_img_size = getimagesize($url_background);
            //dump($target_img_size);
            $head_img = Imagecreatefromjpeg($url_head);
            $qrcode_img = Imagecreatefromjpeg($url_qrcode);

            $center_x = ($target_img_size[0] - 380) / 2;

            //imagecopy php原生图片处理函数 拷贝图像的一部分
            //下例中：即拷贝qrcode_img 图像
            imagecopy($target_img, $qrcode_img, $center_x, 280, 0, 0, 380, 380);
            imagecopy($target_img, $head_img, $center_x, 90, 0, 0, 150, 150);

            //生成新图片名称
            $create_img_url = THINK_PATH . "../Public/front/headimg/6069.jpg";

            //用户字符串昵称    
            $nickname = '用户字符串昵称';

            //定义字体名称。有些字体不能显示汉字，多试几次！
            $font = "C:\Windows\Fonts\msyhbd.ttf";

            $font_color = imagecolorallocate($target_img, 120, 180, 0); //字体颜色
            $font_color2 = imagecolorallocate($target_img, 250, 180, 0); //字体颜色
            imagefttext($target_img, 15, 0, 320, 130, $font_color, $font, '我是:');
            imagefttext($target_img, 15, 0, 320, 180, $font_color, $font, '我的啊名字很长1很长2很长3很长4');
            imagefttext($target_img, 15, 0, 320, 220, $font_color2, $font, '级别:');
            imagefttext($target_img, 20, 0, 380, 220, $font_color2, $font, $lvl_name);
            imagefttext($target_img, 20, 0, 240, 700, $font_color, $font, '与我同行');
            imagefttext($target_img, 20, 0, 220, 750, $font_color, $font, '打开财富密码');

            $create_img = Imagejpeg($target_img, $create_img_url, 100);
            imagepng($create_img_url);
            //     $src = 'Public/front/headimg/' . $this->uid . '.jpg';
        }

        $this->assign('src', "\Public/front/headimg/6069.jpg");

        $this->display();
    }

}
